import CryptoJS from 'crypto-js';

// AES CFB 加密
export function aesEncryptCFB(plainText: string, key: string, iv: string) {
  const keyUtf8 = CryptoJS.enc.Utf8.parse(key);
  const ivUtf8 = CryptoJS.enc.Utf8.parse(iv);

  const encrypted = CryptoJS.AES.encrypt(plainText, keyUtf8, {
    iv: ivUtf8,
    mode: CryptoJS.mode.CFB,
    padding: CryptoJS.pad.NoPadding, // CFB一般不填充
  });

  return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
}

// AES CFB 解密
export function aesDecryptCFB(cipherText: string, key: string, iv: string) {
  const keyUtf8 = CryptoJS.enc.Utf8.parse(key);
  const ivUtf8 = CryptoJS.enc.Utf8.parse(iv);

  const decrypted = CryptoJS.AES.decrypt(
    { ciphertext: CryptoJS.enc.Base64.parse(cipherText) } as any,
    keyUtf8,
    { iv: ivUtf8, mode: CryptoJS.mode.CFB, padding: CryptoJS.pad.NoPadding }
  );

  return decrypted.toString(CryptoJS.enc.Utf8);
}

// 示例
const key = '1234567890123456'; // 16字节
const iv = '1234567890123456';  // 16字节
const plain = 'HelloWorld';

const cipher = aesEncryptCFB(plain, key, iv);
console.log('加密:', cipher);

const decrypted = aesDecryptCFB(cipher, key, iv);
console.log('解密:', decrypted);